<template>
	<view class="container">
		<form @submit="submitForm" class="form">
			<view class="formBox">
				<page-head title="form"></page-head>
				<view class="uni-padding-wrap uni-common-mt">
					<form @submit="formSubmit" @reset="formReset">
						<!-- 正面照 -->
						<view class="formItem" v-if="!info.idcardBack">
							<image class="zm" src="/static/zhengmian.png" @click="handlezm"></image>
						</view>
						<view class="formItem" v-if="info.idcardBack">
							<text><text class="bt">*</text>{{ app.language.jmcarz }}:</text>
							<view class="hjbImg">
								<button type="default" @click="chooseImg(1)">{{ app.language.scimg }}</button>
							</view>
							<view class="scimageBox" v-if="idcardBack.length>0">
								<view class="del" @click="delImg(idcardBack,1)">
									<image class="delImg" src="/static/dels.png"></image>
								</view>
								<image class="scimage" :src="imgUrl+item" v-for="(item,index) in idcardBack"
									:key='index' @click="previewImg(item)"></image>
							</view>
						</view>
						<!-- 反面照 -->
						<view class="formItem" v-if="!info.idcardFront">
							<image class="zm" src="/static/fm.png" @click="handlefm"></image>
						</view>
						<view class="formItem" v-if="info.idcardFront">
							<text><text class="bt">*</text>{{ app.language.jmcarf }}:</text>
							<view class="hjbImg">
								<button type="default" @click="chooseImg(2)">{{ app.language.scimg }}</button>
							</view>
							<view class="scimageBox" v-if="idcardFront.length>0">
								<view class="del" @click="delImg(idcardFront,2)">
									<image class="delImg" src="/static/dels.png"></image>
								</view>
								<image class="scimage" :src="imgUrl+item" v-for="(item,index) in idcardFront"
									:key='index' @click="previewImg(item)"></image>
							</view>
						</view>
						<!-- 姓名 -->
						<view class="formItem1">
							<text><text class="bt">*</text>{{ app.language.name }}:</text>
							<view class="formB">
								<input type="text" disabled  v-model="info.userName" :placeholder="app.language.Iname" />
							</view>
						</view>
						<!-- 联系电话 -->
						<view class="formItem1">
							<text><text class="bt">*</text>{{ app.language.phone }}:</text>
							<view class="formB">
								<input type="phone" disabled v-model="info.phonenumber"
									:placeholder="app.language.Iphone" />
							</view>
						</view>
						<!-- 身份证号 -->
						<view class="formItem1">
							<text><text class="bt">*</text>{{ app.language.card }}:</text>
							<view class="formB">
								<input type="text" disabled v-model="info.idcard" :placeholder="app.language.Icard" />
							</view>
						</view>
						<!-- 上传身份测试 -->
						
						<!-- 提交 -->
						<view class="uni-btn-v">
							<button @click="submit" class="btn">提交修改</button>
							<!-- <button type="default" form-type="reset">Reset</button> -->
						</view>
					</form>
				</view>
			</view>
		</form>
	</view>
</template>

<script>
	import {
		updateQzUser,
		userInfo
	} from '@/api/user.js'
	import config from '@/config'
	const global = getApp().globalData;

	export default {
		data() {
			return {
				imgUrl: config.baseUrl,
				app: {
					global: global,
					name: global.appName,
					language: global.language
				},
				token: "",
				hrUuid: "",
				info: {
					chooseImags: []
				},
				srcImg: [],
				// 工作照
				photo: "",
				idcardBack: [],
				idcardFront: [],
				phone: "",
				uuid: "",
				eventChannel:{}
			}
		},
		onLoad() {
			this.getToken()
			// setTimeout(() => {
			// 	this.getInfo()
			// }, 500); // 1000毫秒后执行
		},
		methods: {
			// 获取token
			getToken() {
				let that = this
				uni.getStorage({
					key: 'loginData',
					success: function(res) {
						that.token = res.data.userInfo.appToken
						that.phone = res.data.phone
						if(that.token){
							that.getInfo()
						}else{
							uni.navigateTo({
								url: '../login/login',
							});
						}
					}
				});
			},

			// 获取用户信息
			getInfo() {
				uni.showLoading({
					title: this.app.language.jzz,
				});
				// 获取最新的用户信息
				let data = {
					phonenumber: this.phone
				}
				userInfo(data).then((res) => {
					uni.hideLoading();
					this.info = res.data[0]
					this.uuid = res.data[0].uuid;
					if (this.info.idcardFront) {
						this.idcardFront = this.info.idcardFront.split(',')
					}
					if (this.info.idcardBack) {
						this.idcardBack = this.info.idcardBack.split(',')
					}
					if (this.info.photop) {
						this.photo = this.imgUrl + this.info.photop
					} else if (!this.info.photop) {
						this.photo = "/static/tx.png"
					}
					console.log('this.info1111111', this.info)
				})
			},
			
			// 上传正面照
			handlezm(){
				uni.navigateTo({
					url: '../user/idcard',
					events: {
					      // 接收数据的回调
					      idCardData: (data) => {
					        this.handleIdCardData(data);
					      }
					    },
					    success: (res) => {
							console.log('res.eventChannel',res.eventChannel)
					      // 保存事件通道
					      this.eventChannel = res.eventChannel;
					    }
				});
			},
			// 上传反面照
			handlefm(){
				uni.navigateTo({
					url: '../user/idcardf',
					events: {
					      // 接收数据的回调
					      idCardData: (data) => {
					        this.handleIdCardDataf(data);
					      }
					    },
					    success: (res) => {
							console.log('res.eventChannel',res.eventChannel)
					      // 保存事件通道
					      this.eventChannel = res.eventChannel;
					    }
				});
			},
			handleIdCardData(data) {
			  console.log('收到身份证数据:', data);
			  // 填充表单数据
			  this.info.userName = data.idcard_res.name.text;
			  this.info.idcard = data.idcard_res.id.text;
			  this.info.idcardBack = data.img
			  this.idcardBack.push(data.img)
			  console.log('this.info.idcardBack',this.info.idcardBack)
			  uni.showToast({
			    title: this.app.language.cg,
			    icon: 'success'
			  });
			},
			
			handleIdCardDataf(data) {
			  console.log('收到身份证数据:', data);
			  // 填充表单数据
			  this.info.idcardFront = data.img
			  this.idcardFront.push(data.img)
			  console.log('this.info.idcardFront',this.info.idcardFront)
			  uni.showToast({
			    title: this.app.language.cg,
			    icon: 'success'
			  });
			},
			
			// 上传图片
			chooseImg(item) {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						let tempFilePaths = res.tempFilePaths;
						// this.tempFilePathList = res.tempFilePaths;
						let base64List = this.info.chooseImags;
						// 图片路径转换成base64格式
						tempFilePaths.forEach((item, index) => {
							uni.getFileSystemManager().readFile({
								filePath: item, // 图片文件路径
								encoding: 'base64', // 编码格式为base64
								success: res => { // 成功回调
									let base64 = 'data:image/jpeg;base64,' + res
										.data; // 拼接data URI
									base64List.push(base64);
									if (base64List.length === tempFilePaths.length) {
										this.info.chooseImags = base64List;
									}
								},
								fail: err => {
									console.error('读取文件失败', err);
								}
							});
						});

						// 上传图片并返回路径
						let imgList = [];
						// 上传前显示加载中
						uni.showLoading({
							title: this.app.language.jzz,
						});
						tempFilePaths.forEach((tempFilePaths) => {
							console.log('tempFilePaths',tempFilePaths)
							const uploadTask = uni.uploadFile({
								url: 'https://mqzhian.cn:8088/common/upload', // 你的ThinkPHP服务器地址
								filePath: tempFilePaths,
								name: 'file', // 这里根据服务器接收的字段来定义
								success: (uploadFileRes) => {
									const data = JSON.parse(uploadFileRes.data);
									console.log('上传成功', data);
									// 上传成功后隐藏加载中
									uni.hideLoading();
									// 这里处理返回的图片路径，例如保存到数组中
									imgList.push(data.fileName);
									if (item == 1) {
										this.idcardBack = imgList
										this.info.idcardBack = imgList.join(',')
										console.log('this.info.idcardBack',this.info.idcardBack)
										let tokenData = {
											grant_type:"client_credential",
											appid:"wx6d06ad1a151b430a",
											secret:"0c91dfaa50b332635548af273337c2b1"
										}
										uni.request({
											url: `https://api.weixin.qq.com/cgi-bin/token`,
											method: 'GET',
											data: tokenData,
											success: (res) => {
												console.log('token1111:', res.data.access_token);
												if(res.data.access_token){
													const postData = {
													 "service" : "wx79ac3de8be320b71",
													   "api" : "OcrAllInOne",
													   "data" : {
													     "img_url": 'https://mqzhian.cn:8088'+this.info.idcardBack,
													     "data_type": 3,
													     "ocr_type": 1
													   },
													   "client_msg_id" : "id123"
													};
													uni.request({
														url: `https://api.weixin.qq.com/wxa/servicemarket?access_token=`+res.data.access_token,
														method: 'POST',
														data: postData,
														success: (res) => {
															if(res.data.errmsg=="ok"){
																console.log('身份识别结果:', res.data.data);
																// 假设 res.data 是混乱的字符串
																let rawData = res.data.data;
																// 尝试替换错误字符（根据实际情况调整）
																rawData = rawData.replace(/%/g, '').replace(/\\"/g, '"');
																// 尝试解析为 JSON
																try {
																  const parsedData = JSON.parse(rawData);
																  this.info.userName = parsedData.idcard_res.name.text
																  this.info.idcard = parsedData.idcard_res.id.text
																} catch (e) {
																  console.error('解析失败:', e);
																}
															}else{
																uni.showToast({
																	title: this.app.language.shibai,
																	icon: 'success',
																});
															}
															
														},
														fail: (res) => {}
													})
												}
											},
											fail: (res) => {}
										})
										
									} else if (item == 2) {
										this.idcardFront = imgList
										this.info.idcardFront = imgList.join(',')
									}
								},
								fail: (error) => {
									console.error('上传失败', error);
									uni.showToast({
										title: '上传失败',
										icon: 'none',
									});
								}
							});
						});
					}
				})
			},

			// 删除图片
			delImg(list, id) {
				uni.showModal({
					title: this.app.language.titDel, // 弹框标题
					content: this.app.language.delBtn, // 弹框内容
					cancelText: '取消', // 取消按钮文本
					confirmText: '确定', // 确认按钮文本
					success: (res) => {
						if (res.confirm) {
							// 用户点击了“确定”按钮
							if (id == 1) {
								this.idcardBack = []
								this.info.idcardBack = ""
							} else if (id == 2) {
								this.idcardFront = []
								this.info.idcardFront = ""
							}
						} else if (res.cancel) {
							// 用户点击了“取消”按钮，或者关闭了弹框
							console.log('用户取消删除');
						}
					}
				});
			},

			// 提交数据
			submit() {
				if (this.uuid) {
					if (!this.info.userName) {
						uni.showToast({
							title: this.app.language.Iname,
							icon: 'none',
						});
						return
					}
					if (!this.info.phonenumber) {
						uni.showToast({
							title: this.app.language.Iphone,
							icon: 'none',
						});
						return
					}
					if (!this.info.idcard) {
						uni.showToast({
							title: this.app.language.Icard,
							icon: 'none',
						});
						return
					}
					if (this.info.idcardBack.length == 0) {
						uni.showToast({
							title: this.app.language.ijmcarz,
							icon: 'none',
						});
						return
					}
					if (this.info.idcardFront.length == 0) {
						uni.showToast({
							title: this.app.language.jmcarf,
							icon: 'none',
						});
						return
					}
				}
				let data = {
					uuid: this.uuid,
					appToken:this.token,
					idcard: this.info.idcard,
					idcardBack: this.info.idcardBack,
					idcardFront: this.info.idcardFront,
					userName: this.info.userName,
					phonenumber: this.info.phonenumber
				}
				uni.showLoading({
					title: this.app.language.jzz,
				});
				updateQzUser(this.info).then((res) => {
					if (res.code == 200) {
						uni.clearStorageSync();
						let loginData = {
							userInfo:{
								appToken:this.token,
								uuid: this.uuid,
								idcard: this.info.idcard,
								idcardBack: this.info.idcardBack,
								idcardFront: this.info.idcardFront,
								userName: this.info.userName,
								phonenumber: this.info.phonenumber,
								peopleType:"people"
							}
						}
						uni.setStorage({
							key: 'loginData',
							data: loginData,
							success: function() {
								console.log('存储成功')
							}
						});
						uni.hideLoading();
						uni.showToast({
							title: this.app.language.success,
							icon: 'success',
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1000);
					}
				})
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
	}

	.form {
		box-shadow: 1px 1px 10rpx #ddd;
		/* display: block; */
		width: 100%;
		padding-bottom: 20rpx;
	}

	.formItem {
		margin: 10rpx 0;
		padding: 10rpx;
		/* height: 162rpx; */
		position: relative;
		border-bottom: 1px dashed #ddd
	}

	.infoBox {
		border: 1px solid #ddd;
		padding: 0 20rpx;
		box-shadow: 1px 1px 10rpx #ddd;
	}

	.infoBox1 {
		border: 1px solid #ddd;
		margin-top: 20rpx;
		padding: 0 15rpx;
		box-shadow: 1px 1px 10rpx #ddd;
	}

	.formItem1 {
		margin: 10rpx 0;
		padding: 22rpx 10rpx;
		/* height: 162rpx; */
		position: relative;
		border-bottom: 1px dashed #ddd
	}

	.container {
		padding: 20rpx;
	}

	.form {
		box-shadow: 1px 1px 10rpx #ddd;
		/* display: block; */
		width: 100%;
		padding-bottom: 20rpx;
	}

	.formItem {
		margin: 10rpx 0;
		padding: 10rpx;
		/* height: 162rpx; */
		position: relative;
		border-bottom: 1px dashed #ddd
	}

	.infoBox {
		border: 1px solid #ddd;
		padding: 0 20rpx;
		box-shadow: 1px 1px 10rpx #ddd;
	}

	.infoBox1 {
		border: 1px solid #ddd;
		margin-top: 20rpx;
		padding: 0 15rpx;
		box-shadow: 1px 1px 10rpx #ddd;
	}

	.formItem1 {
		margin: 10rpx 0;
		padding: 10rpx;
		/* height: 162rpx; */
		position: relative;
		border-bottom: 1px dashed #ddd
	}

	.formB {
		/* background-color: #f3f3f3; */
		font-size: 24rpx;
		padding: 10rpx;
		margin-top: 10rpx;
		position: absolute;
		right: 10rpx;
		top: -2rpx;
		text-align: right;
		color: #808080;
	}

	.formC {
		font-size: 24rpx;
		padding: 10rpx;
		margin-top: 10rpx;
		border: 1px solid #ddd;
		height: 117rpx;
	}

	.formItem text,
	.formItem1 text {
		font-size: 26rpx;
	}

	.hjbImg button {
		font-size: 22rpx;
		width: 149rpx;
		height: 56rpx;
		background: #2f8ef9;
		color: #fff;
	}

	.hjbImg {
		/* position: absolute;
		bottom: 10rpx; */
		width: 150rpx;
		margin-top: 20rpx;
	}

	.scimageBox {
		display: inline-block;
		width: 100%;
		height: 100rpx;
		position: relative;
		/* text-align: center; */
	}

	.scimage {
		width: 121rpx;
		height: 80rpx;
		margin-right: 10rpx;
		margin-top: 5px;
		border-radius: 5rpx;
	}

	.title {
		margin-top: 30rpx;
		font-weight: bold;
		font-size: 28rpx;
	}

	.submit {
		background-color: #2f8ef9;
		color: #fff;
		font-size: 28rpx;
		width: 95%;
		margin: 20rpx auto 0;
	}

	.picker {
		padding: 10px;
		text-align: right;
		margin-top: -25rpx;
	}

	.bt {
		color: red;
		margin-right: 5rpx;
	}

	.picker {
		width: 260rpx;
		color: #808080;
	}

	.del {
		color: red;
		font-size: 26rpx;
		text-align: right;
		width: 50rpx;
		height: 50rpx;
		position: absolute;
		right: 0;
		top: -43rpx;
	}

	.delImg {
		width: 50rpx;
		height: 50rpx;
	}


	.btn {
		font-size: 27rpx;
		width: 100%;
		background: #2f8ef9;
		color: #fff;
		margin-top: 20rpx;
	}
	
	.zm{
		width: 100%;
		height: 375rpx;
	}
</style>